package cn.jtool.dig.client.comm.virtual;

import cn.jtool.dig.client.comm.MessageExchange;
import cn.jtool.dig.client.comm.tunnel.TunnelAttrKey;
import cn.jtool.dig.common.model.Commands;
import cn.jtool.dig.common.model.Packet;
import cn.jtool.dig.common.model.PacketBody;
import cn.jtool.dig.common.model.PacketHeader;
import cn.jtool.dig.common.netty.SNGenerator;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Getter
@Slf4j
@Component
@ChannelHandler.Sharable
public class VirtualDataHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            ByteBuf buf = (ByteBuf) msg;
            byte[] bytes = new byte[buf.readableBytes()];
            buf.getBytes(0, bytes);
            PacketHeader packetHeader = new PacketHeader();
            packetHeader.setCommand(Commands.DATA_TRANSPARENT.getCode());
            packetHeader.setChannelId(ctx.channel().attr(TunnelAttrKey.SESSION_ID).get());
            packetHeader.setDigId(0x00);
            packetHeader.setSn(SNGenerator.gen());
            PacketBody body = new PacketBody(bytes);
            Packet packet = Packet.builder().header(packetHeader).body(body).build();
            MessageExchange.toReal(packet);
        } catch (Exception e){
            log.error("[virtual]消息转发异常",e);
        }
    }


}
